﻿using LmgCMS.Middleware;
using LmgCMS.Service;
using Microsoft.AspNetCore.Mvc;
using System.Text;

namespace LmgCMS.Controllers
{
    [TempleteFilter]
    [ApiExplorerSettings(IgnoreApi = true)]
    public class HomeController : Controller
    {
        private readonly INewsService _newsService;
        private readonly INewsDataService _newsdataService;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ISiteService _siteService;
        public HomeController(INewsService newsService, INewsDataService newsdataService, ISiteService siteService, IWebHostEnvironment webHostEnvironment)
        {
            _newsService = newsService;
            _newsdataService = newsdataService;
            _siteService = siteService;
            _webHostEnvironment = webHostEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        #region SiteMap
        /// <summary>
        /// 获取RSS
        /// </summary>
        /// <param name="category">分类</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SiteMap()
        {
            string url = HttpContext.Request.Host.Host;
            string siteName = "luomingui";
            string desc = "";
            var siteInfo = _siteService.Find(x => x.SiteUrl == url && x.IsOpen == 1);
            if (siteInfo != null)
            {
                siteName = siteInfo.Name;
                desc = siteInfo.SeoDescribe;
            }
            var articleList = _newsService.GetNewsLast(51);  //获取需要生成sitemmap的数据
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?> ");
            builder.AppendLine("<siteMap xmlns=\"http://schemas.microsoft.com/AspNet/SiteMap-File-1.0\" > ");
            builder.AppendLine("<siteMapNode url=\""+ url + "\" title=\"您现在的位置：首页\" description=\"网站首页\"> ");
            foreach (var item in articleList)
            {
                var spriderUrl = url + string.Format("/News/Faq/Show/{0}", item.ID);
                builder.AppendLine("<siteMapNode url=\"" + spriderUrl + "\" title=\"" + item.Title + "\" description=\"" + item.SmallText + "\" /> ");
            }
            builder.AppendLine("</siteMapNode> ");
            builder.AppendLine("</siteMap> ");

            return new ContentResult
            {
                Content = builder.ToString(),
                ContentType = "application/xml",
                StatusCode = 200
            };
        }
        #endregion
    }
}